class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return vector<int>();
        }
        int n = matrix.size();
        int m = matrix[0].size();
        int r = 0;
        int c = 0;
        int rLen = n;
        int cLen = m;
        vector<int> ans;

        while (rLen > 0 && cLen > 0) {
            if (rLen == 1) {
                for (int j = 0; j < cLen; ++j) {
                    ans.push_back(matrix[0 + r][j + c]);
                }
            } else if (cLen == 1) {
                for (int i = 0; i < rLen; ++i) {
                    ans.push_back(matrix[i + r][0 + c]);
                }
            } else {
                for (int j = 0; j < cLen; ++j) {
                    ans.push_back(matrix[0 + r][j + c]);
                }
                for (int i = 1; i < rLen - 1; ++i) {
                    ans.push_back(matrix[i + r][cLen - 1 + c]);
                }
                for (int j = cLen - 1; j >= 0; --j) {
                    ans.push_back(matrix[rLen - 1 + r][j + c]);
                }
                for (int i = rLen - 2; i > 0; --i) {
                    ans.push_back(matrix[i + r][0 + c]);
                }
            }
            rLen -= 2;
            cLen -= 2;
            ++r;
            ++c;
        }
        return ans;
    }
};
